import 'package:flutter/material.dart';
import 'package:english_words/english_words.dart';

class Home extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new HomeWidget();
  }
}

class HomeWidget extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return new HomeState();
  }
}

class HomeState extends State<HomeWidget> {
  final _words = <WordPair>[];
  final _saved = <WordPair>[];
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('首页'),
        actions: <Widget>[
          new IconButton(icon: new Icon(Icons.list), onPressed: _pushSaved), 
          //可以试试添加这两行后APP上有什么效果
          new IconButton(icon: new Icon(Icons.add), onPressed: _pushSaved), 
          new IconButton(icon: new Icon(Icons.create), onPressed: _pushSaved), 
        ],
      ),
      
      body: _buildWords()
    );
  }
  
  void _pushSaved() {
    Navigator.of(context).push(
      new MaterialPageRoute(
        builder: (c) {
          final tiles = _saved.map((pair){
            return new ListTile(
              title: new Text(pair.asPascalCase),
            );
          });
          final dividedTiles = ListTile.divideTiles(
            context: c,
            tiles: tiles
          ).toList();
          return new Scaffold(
            appBar: new AppBar(
              title: new Text('收藏列表'),
            ),
            body: new ListView(children: dividedTiles),
          );
        },
      )
    );
  }

  Widget _buildWords() {
    return new ListView.builder(
      itemBuilder: (itemContext, i) {
        if(i.isOdd) return new Divider();
        final index = i ~/ 2;
        if(index >= _words.length){
          _words.addAll(generateWordPairs().take(10));
        }
        return _buildRow(_words[index]);
      },
    );
  }

  Widget _buildRow(WordPair pair) {
    final saved = _saved.contains(pair);
    return new ListTile(
      title: new Text(
        pair.asPascalCase
      ),
      trailing: new Icon(
        saved ? Icons.favorite : Icons.favorite_border,
        color: saved ? Colors.red : null,
      ),
      onTap: () {
        setState(() {
          if(saved){
            _saved.remove(pair);
          }
          else{
            _saved.add(pair);
          }
        });
      },
    );
  }
}
